package com.example.weiji_1.datebase;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import java.io.InputStream;
import java.text.*;

import org.w3c.dom.Text;

import wordroid.model.Massage;
import wordroid.model.TextList;
import wordroid.model.Texts;
import wordroid.model.UnitList;
import wordroid.model.Units;



public class DataAccess {
	public  static String bookID="";           //选定的书
	public  static String listID;            //选定的List
	public  static int NumOfStudy;        //学习的数
	public  Context context;
	private SqlHelper helper;
	public static boolean ifContinue;
	
	public  DataAccess(Context context){
		helper = new SqlHelper();
		Cursor cursor =null;
		cursor=helper.Query(context, SqlHelper.RECORD_TABLE, null, null, null, null, null, null);
		if (cursor==null)NumOfStudy=0;
		else if(cursor.getCount()==0)
			NumOfStudy=0;
		else if(cursor.moveToLast())
			NumOfStudy=Integer.parseInt(cursor.getString(0));
		
		cursor.close();
		this.context = context;
		
	}
	
	/*
	 * 初始化词库
	 * 
	 * 参数：
	 * bookname：词库名称
	 * list：所有单词
	 * numOfList:list的数量
	 */
	public boolean initBook(String bookname,ArrayList<Massage> list,String numOfList,String NewName) throws Exception{
		boolean success = false;
		String bookName = null;
		 bookName=NewName;
		Cursor cursor=helper.Query(context, SqlHelper.TEST_TABLE, null, null, null, null, null, null);
		String bookID="book1";
		if (cursor.moveToLast()){
			StringTokenizer st = new StringTokenizer(cursor.getString(0), "book");
			bookID="book"+(Integer.parseInt(st.nextToken())+1);
		}
		//ImportBook.result=bookID;
		cursor.close();
	    Calendar cal = Calendar.getInstance();
	    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
	    String date=f.format(cal.getTime());
	    ContentValues cv =new ContentValues();
	    helper.CreateTable(context, bookID);
	    for (int i=0;i<list.size();i++){
	    	if (ifContinue){
	    		cv.put("ID",list.get(i).getID() );
		    	//cv.put("SPELLING", list.get(i).getSpelling());
		    	//cv.put("MEANNING", list.get(i).getMeanning());
		    	//cv.put("PHONETIC_ALPHABET", list.get(i).getPhonetic_alphabet());
		    	//cv.put("LIST", list.get(i).getList());
		    	helper.Insert(context, bookID, cv);
		    	//Log.i("Inserting word:",list.get(i).getSpelling());
	    	}
	    	else return false;
	    }
	    UnitList wordList = new UnitList();
	     f = new SimpleDateFormat("yyyy-MM-dd");
	     
		for (int i=0;i<Integer.parseInt(numOfList);i++){
			if (ifContinue){
				//wordList.setBestScore("");
				//wordList.setBookID(bookID);
				wordList.setLearned("0");
				//wordList.setLearnedTime("");
				//wordList.setList(String.valueOf(i+1));
				//wordList.setReview_times("0");
				//wordList.setReviewTime("");
				//wordList.setShouldReview("0");
				this.InsertIntoList(wordList);
			}
			else return false;
			
//			Log.i("Inserting list", wordList.getList());
		}
		DataAccess.bookID=bookID;
		cv.clear();
		cv.put("ID", bookID);
	    cv.put("NAME", bookName);
	    cv.put("GENERATE_TIME", date);
	    cv.put("NUMOFLIST", numOfList);
	    cv.put("NUMOFWORD", list.size());
	    helper.Insert(context, SqlHelper.MASSAGE_TABLE, cv);
		Log.i("select", DataAccess.bookID);
		success=true;
	    return success;
	}
	
	/*
	 *查询词库
	 *参数
	 *selection：查询条件（where语句）
	 *selectionArgs:where中包含的“？”
	 */
	public ArrayList<UnitList> QueryUnit(String selection,String[] selectionArgs){

		Cursor cursor=helper.Query(context, SqlHelper.UNIT_TABLE, null, selection, selectionArgs, null, null, null);
		ArrayList<UnitList> list= new ArrayList<UnitList>();;
        if (cursor.moveToFirst()){
        	do{
        		UnitList bl=new UnitList();
        		bl.setunitID(cursor.getString(0));
        		bl.setallnum(cursor.getString(1));
        		bl.setLearned(cursor.getString(2));
        		list.add(bl);
        		}
            while(cursor.moveToNext());
        }
        cursor.close();
		return list;
		
	}
	
	public ArrayList<Texts> Text(String selection,String[] selectionArgs){

		Cursor cursor=helper.Query(context, SqlHelper.TEXT2, null, selection, selectionArgs, null, null, null);
		ArrayList<Texts> list= new ArrayList<Texts>();;
        if (cursor.moveToFirst()){
        	do{
        		Texts b6=new Texts();
        		b6.setID(cursor.getString(0));
        		b6.setquestion(cursor.getString(1));
        		b6.setanswer(cursor.getString(4));
        		list.add(b6);
        		}
            while(cursor.moveToNext());
        }
        cursor.close();
		return list;
		
	}
	
	public ArrayList<Units> Unit(String selection,String[] selectionArgs){

		Cursor cursor=helper.Query(context, SqlHelper.UNIT1, null, selection, selectionArgs, null, null, null);
		ArrayList<Units> list= new ArrayList<Units>();;
        if (cursor.moveToFirst()){
        	do{
        		Units b6=new Units();
        		b6.setID(cursor.getString(0));
        		b6.setinclude(cursor.getString(1));
        		b6.setxiaojie(cursor.getString(2));
        		list.add(b6);
        		}
            while(cursor.moveToNext());
        }
        cursor.close();
		return list;
		
	}
   
   
	/*
     * 查询单词
     * 参数
     *selection：查询条件（where语句）
	 *selectionArgs:where中包含的“？”
     */
	public ArrayList<Massage> QueryMsg(String selection,String[] selectionArgs){
		Cursor cursor =helper.Query(context, SqlHelper.MASSAGE_TABLE, null, selection, selectionArgs, null, null, null);
        ArrayList<Massage> list = new ArrayList<Massage>();
        if (cursor.moveToFirst()){
          	do{
        		Massage massage=new Massage();
        		massage.setID(cursor.getString(0));
        		massage.setMessage(cursor.getString(1));
        		//massage.setMeanning(cursor.getString(2));
        		//massage.setPhonetic_alphabet(cursor.getString(3));
        		//massage.setList(cursor.getString(4));
        		list.add(massage);
    //    		Log.i("Querying word:",word.getSpelling());
        		}
            while(cursor.moveToNext());
        }
        cursor.close();
		return list;
		
	}
	
	/*
	 * 查询list完成情况
	 * 参数
	 * selection：查询条件（where语句）
	 *selectionArgs:where中包含的“？”
	 */
	public ArrayList<TextList> QueryText(String selection,String[] selectionArgs){
		Cursor cursor=helper.Query(context, SqlHelper.TEST_TABLE, null, selection, selectionArgs, null, null, null);
		ArrayList<TextList> list = new ArrayList<TextList>();
		if (cursor.moveToFirst()){
        	
        	
        	do{
        		TextList wl=new TextList();
        		wl.setID(cursor.getString(0));
        		wl.setlearned(cursor.getString(1));
        		wl.setallnum(cursor.getString(2));
        		list.add(wl);
        		}
            while(cursor.moveToNext());
        }
		cursor.close();

		return list;
		
	}
	
	/*
	 * 更新list完成情况
	 * 参数
	 * list：要进行更新的list（新数据）
	 */
	public void UpdateList(UnitList list){
		ContentValues cv = new ContentValues();
		//cv.put("BOOKID", list.getBookID());
		//cv.put("LIST", list.getList());
		cv.put("LEARNED", list.getLearned());
		//cv.put("LEARN_TIME", list.getLearnedTime());
		//cv.put("REVIEW_TIMES", list.getReview_times());
		//cv.put("REVIEWTIME", list.getReviewTime());
		//cv.put("BESTSCORE", list.getBestScore());
		//cv.put("SHOULDREVIEW", list.getShouldReview());
		
		//helper.Update(context, SqlHelper.RECORD_TABLE, cv, " BOOKID ='"+list.getBookID()+"'AND LIST ='"+list.getList()+"'", null);
	}
	
	/*
	 * 删除list完成情况
	 * 参数
	 * list：要删除的list
	 */
	public void DeleteBook(){
		helper.Delete(context, SqlHelper.DB_NAME, "BOOKID ='"+DataAccess.bookID+"'", null);
		helper.Delete(context, SqlHelper.DB_NAME, "ID ='"+DataAccess.bookID+"'", null);
		helper.DeleteTable(context, DataAccess.bookID);
	}
	
	/*
	 * 加入生词本
	 * 参数
	 * word：要添加的单词
	 */
	public void InsertIntoAttention(Massage massage){
		ContentValues cv = new ContentValues();
		cv.put("ID", String.valueOf(DataAccess.NumOfStudy+1));
		//cv.put("SPELLING", massage.getSpelling());
		//cv.put("MEANNING", massage.getMeanning());
		//cv.put("PHONETIC_ALPHABET", massage.getPhonetic_alphabet());
		cv.put("LIST", "Attention");
		helper.Insert(context, SqlHelper.TEST_TABLE, cv);
		
	}
	
	/*
	 * 删除生词本中的单词
	 * 参数
	 * word：要添加的单词
	 */
	public void DeleteFromAttention(Massage massage){
		helper.Delete(context, SqlHelper.TEST_TABLE, "ID ='"+massage.getID()+"'", null);
	}
	
	/*
	 * 查询生词本
	 * selection：查询条件（where语句）
	 * selectionArgs:where中包含的“？”
	 */
	
	
	public ArrayList<Massage> QueryAttention(String selection,String[] selectionArgs){
		Cursor cursor =helper.Query(context, SqlHelper.RECORD_TABLE, null, selection, selectionArgs, null, null, null);
        ArrayList<Massage> list = new ArrayList<Massage>();
        if (cursor.moveToFirst()){
        	
        	
        	do{
        		Massage massage=new Massage();
        		massage.setID(cursor.getString(0));
        		//massage.setSpelling(cursor.getString(1));
        		//massage.setMeanning(cursor.getString(2));
        		//massage.setPhonetic_alphabet(cursor.getString(3));
        		//massage.setList(cursor.getString(4));
        		list.add(massage);
      //  		Log.i("Querying word:",word.getSpelling());
        		}
            while(cursor.moveToNext());
        }
        cursor.close();
		return list;
	}
	
	/*
	 * 加入list完成情况
	 * 参数
	 * list:要加入的list条目
	 */
	public void InsertIntoList(UnitList list){
		ContentValues cv = new ContentValues();
		//cv.put("BOOKID", list.getBookID());
		//cv.put("LIST", list.getList());
		cv.put("LEARNED", list.getLearned());
		//cv.put("LEARN_TIME", list.getLearnedTime());
		//cv.put("REVIEW_TIMES", list.getReview_times());
		//cv.put("REVIEWTIME", list.getReviewTime());
		//cv.put("BESTSCORE", list.getBestScore());
		//cv.put("SHOULDREVIEW", list.getShouldReview());
		helper.Insert(context, SqlHelper.TEST_TABLE, cv);
		
	}
	
	public void ResetBook(){
		ArrayList<UnitList> list = new ArrayList<UnitList>();
		//list=this.QueryList("BOOKID ='"+DataAccess.bookID+"'", null);
		for (int i=0;i<list.size();i++){
			UnitList newlist = list.get(i);
			//newlist.setBestScore("");
			newlist.setLearned("0");
			//newlist.setLearnedTime("");
			//newlist.setReview_times("0");
			//newlist.setReviewTime("");
			//newlist.setShouldReview("0");
			this.UpdateList(newlist);
			
		}
	}
	
	public void UpdatePart1(UnitList text1){
		ContentValues cv = new ContentValues();
		cv.put("identifier", text1.getunitID());
		cv.put("question_inc", text1.getallnum());
		cv.put("MEANNING", text1.getLearned());
		//cv.put("PHONETIC_ALPHABET", massage.getPhonetic_alphabet());
		//cv.put("LIST", massage.getList());
		helper.Update(context, SqlHelper.UNIT_TABLE, cv, "ID ='"+text1.getunitID()+"'", null);
	}
 }
